package com.cln.reverse_string;

import java.util.Stack;

public class StringReverser {

	private String inputString;
	private String splitToken = " ";

	public StringReverser(String inputString) {
		this.inputString = inputString;
	}

	public String reverse() {
		if (IsSplitable(inputString)) {
			String[] splitedStrings = inputString.split(splitToken);
			Stack<String> wordStack = makeStack(splitedStrings);
			return getReversedString(wordStack);
		} else {
			return inputString;
		}
	}

	public boolean IsSplitable(String inputString) {
		if (inputString.trim().length() == 0)
			return false;
		else
			return true;
	}

	private Stack<String> makeStack(String[] splitedStrings) {
		Stack<String> wordStack = new Stack<String>();
		int wordsCount = splitedStrings.length;
		for (int i = 0; i < wordsCount; i++) {
			wordStack.push(splitedStrings[i]);
			wordStack = pushSplitToken(wordStack, wordsCount, i);
		}
		return wordStack;
	}

	private Stack<String> pushSplitToken(Stack<String> wordStack,
			int stringLength, int loopCount) {
		if (loopCount != stringLength - 1)
			wordStack.push(splitToken);
		return wordStack;
	}

	private String getReversedString(Stack<String> wordStack) {
		String outputString = new String();
		while (!wordStack.empty()) {
			outputString += wordStack.pop();
		}
		return outputString;
	}

}
